package com.sekla.design;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.AlternatePrint")
public class AlternatePrint {
    public static void main(String[] args) {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition flagA = awaitSignal.newCondition();
        Condition flagB = awaitSignal.newCondition();
        Condition flagC = awaitSignal.newCondition();

        Thread t1 = new Thread(() -> {
            awaitSignal.print("a", flagA, flagB);
        });

        Thread t2 = new Thread(() -> {
            awaitSignal.print("b", flagB, flagC);
        });

        Thread t3 = new Thread(() -> {
            awaitSignal.print("c", flagC, flagA);
        });

        t1.start();
        t2.start();
        t3.start();

        log.debug("开始");
        awaitSignal.lock();
        try {
            flagA.signal();
        } finally {
            awaitSignal.unlock();
        }
    }
}

class AwaitSignal extends ReentrantLock {
    private int loopCnt = 0;
    public AwaitSignal(int loopCnt){
        this.loopCnt = loopCnt;
    }

    public void print(String str, Condition current, Condition next) {
        for (int i = 0; i < loopCnt; i++) {
            lock();
            try {
                current.await();
                System.out.println(str);
                next.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                unlock();
            }
        }
    }
}
